package com.powernode.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.entity.SysUser;
import com.powernode.util.JwtUtils;
import com.powernode.vo.HttpResult;
import com.powernode.vo.SecurityUser;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证成功处理器，当用户登录成功后，会执行此处理器
 * 生成JWT，并返回给前端用户
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private ObjectMapper objectMapper; //序列化和反序列化
    @Resource
    private JwtUtils jwtTokenUtil;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 从认证信息中获取登录用户信息s
        SecurityUser securityUser = (SecurityUser)authentication.getPrincipal();
        SysUser sysUser = securityUser.getSysUser();
        String strUserInfo = objectMapper.writeValueAsString(sysUser);
        // 获取用户的权限信息
        List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>)securityUser.getAuthorities();
        // 收集权限信息
        List<String> auths = authorities.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.toList());
        // 生成jwt
        String jwtToken = jwtTokenUtil.createToken(strUserInfo, auths);
        HttpResult result = HttpResult.builder()
                .code(1)
                .msg("jwt生成成功")
                .data(jwtToken)
                .build();
        printToken(request,response,result);
    }

    private void printToken(HttpServletRequest request, HttpServletResponse response, HttpResult result) throws IOException {
        String strResponse = objectMapper.writeValueAsString(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(strResponse);
        writer.flush();
    }

}
